package com.cancer.biz.common.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.core.tools.picocli.CommandLine.ParameterException;
import org.omg.CORBA.SystemException;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * @Company GeekPlus
 * @Project beetle
 * @since 1.0.0
 * @Author  xiyunfeng
 * @Date    2015年10月10日 上午10:21:28
 * @Description 系统统一异常处理类 
 */
public class AppExceptionHandler extends SimpleMappingExceptionResolver {

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.SimpleMappingExceptionResolver#doResolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	public ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("ex", ex);
		//是否异步请求
		if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request.getHeader("X-Requested-With")!= null && request  .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
			    // 根据不同错误转向不同页面
			    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
				if(ex instanceof SystemException) {
					return new ModelAndView("exception/error-system", model);
				}else if(ex instanceof CheckedSystemException) {
					return new ModelAndView("exception/checked-error-system", model);
				}else if(ex instanceof ParameterException) {
					return new ModelAndView("exception/error-parameter", model);
				}else {
					return new ModelAndView("WEB-INF/error", model);
				}
		 }else{	 
			    //返回json串
		 		//设置状态码
		 		response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
		 		//设置ContentType
		 		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		 		//避免乱码
		 		response.setCharacterEncoding("UTF-8");
		 		response.setHeader("Cache-Control","no-cache, must-revalidate");
		
		 		try {
		 			response.getWriter().write("{success:"+0+",msg:"+ex.getMessage()+"}");
		 			//改写为异常定义处理
		 		} catch (IOException e) {
		 			model.put("ex", e);
		 	        return new ModelAndView("WEB-INF/error", model);
		 		}

		 		return null;
		 }

	}
}
